package TuiLayer;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import ControlLayer.LeaseCtr;
import ControlLayer.MachineryCtr;
import ControlLayer.CustomerCtr;
import ModelLayer.Lease;
import ModelLayer.Unit;
import ModelLayer.Customer;
import java.util.Scanner;

/**
 * Vestbjerg project
 * @GroupB2 (UCN - Computer Science DMAJ0914) 
 */
public class LeaseUI
{
    // instance variables
    private LeaseCtr leaseCtr;    
    private MachineryCtr machineryCtr;
    private CustomerCtr customerCtr;
    private Lease lease;

    private int securityLvl;
    private static String masterPassword = Menu.getMasterPassword();

    /**
     * Constructor for objects of class LeaseUI
     */
    public LeaseUI()
    {
        leaseCtr = new LeaseCtr();
        machineryCtr = new MachineryCtr();
        customerCtr = new CustomerCtr();
    }

    public void addLease(Lease lease)
    {
        leaseCtr.addLease(lease);
    }

    public void updateLease(Lease lease, String id, String leaseDate, String returnDate, int period, String state, int discount)
    {
        leaseCtr.updateLease(lease, id, leaseDate, returnDate, period, state, discount);
    }

    public Lease findLease(String id)
    {
        return leaseCtr.findLease(id);
    }

    public void deleteLease(Lease lease)
    {
        leaseCtr.deleteLease(lease);
    }

    public void setSecurityLvl(int securityLvl) 
    {
        this.securityLvl = securityLvl;
    }

    private int getChoice()
    {
        Scanner keyboard = new Scanner(System.in);
        int choice = keyboard.nextInt();

        return choice;
    }

    // Leases menu loop
    public void menuStart() 
    {
        boolean exit = false;
        String print = null;
        while(!exit) 
        {
            writeMenu(print);
            int choice = getChoice();

            if(choice == 1) 
            {
                print = newLeaseMenu();
            }
            else if(choice == 2)
            {
                print = findEditMenu();
            }
            else if(choice == 0)
            {
                exit = true;
            }
            else 
            {
                print = "ERROR!";
            }

        }
    }

    public void writeMenu(String print) 
    {
        System.out.println("\f *** Leases ***");
        System.out.println(" (1)New");
        System.out.println(" (2)Find / Edit");
        System.out.println(" (0)Back");

        if(print != null) 
        {
            System.out.println("\n " + print);

        }
        System.out.print("\n Make your choice: ");
    }

    public String newLeaseMenu() 
    {
        String print = null;
        System.out.println("Enter new lease id: ");
        Scanner sc = new Scanner(System.in);
        String id = sc.next();
        if(!leaseIdExists(id)) {
            System.out.println("Enter current date [DD-MM-YYYY]:");
            String leaseDate = sc.next();

            lease = null;
            lease = new Lease(id,leaseDate);

            boolean exit = false;
            
            while(!exit) 
            {
                writeNewLeaseMenu(print);
                int choice = getChoice();

                if(choice == 1) 
                {
                    print = this.startAddUnit();
                }
                else if(choice == 2)
                {
                    print = this.startRemoveUnit();
                }
                else if(choice == 3)
                {
                    print = this.startSetCustomer();
                }
                else if(choice == 4)
                {
                    print = this.startSetDiscount();
                }
                else if(choice == 5)
                {
                    print = this.startSetPeriod();
                }
                else if(choice == 6) 
                {
                    print = this.startConfirmLease();
                }
                else if(choice == 0)
                {
                    exit = true;
                }
                else 
                {
                    print = "ERROR!";
                }

            }
        }
        else 
        {
            print = "Lease with that ID already exists.";
        }
        return print;
    }

    private boolean leaseIdExists(String id) 
    {

        boolean result = false;
        int counter = 0;
        while(result == false && counter < leaseCtr.getLeaseList().size()) 
        {
            if(leaseCtr.getLeaseList().get(counter).getId().equals(id))
            {
                result = true;
            }
            else 
            {
                counter++;
            }

        }
        return result;

    }

    public void writeNewLeaseMenu(String print) 
    {
        System.out.println("\f *** LEASE ID: " + lease.getId() + " ***");
        System.out.println(" (1)Add unit");
        System.out.println(" (2)Remove unit");
        System.out.println(" (3)Set customer");
        System.out.println(" (4)Set discount");
        System.out.println(" (5)Set period");
        System.out.println(" (6)Confirm lease");
        System.out.println(" (0)Back");

        if(print != null) 
        {
            System.out.println("\n " + print);

        }
        System.out.print("\n Make your choice: ");
    }

    public String startAddUnit() 
    {
        String print = null;

        System.out.println("\nEnter serial number: ");        
        Scanner sc = new Scanner(System.in);
        String serialNumber = sc.next();

        Unit foundUnit = machineryCtr.findUnit(serialNumber);
        if(foundUnit != null) {
            if(foundUnit.isAvailible()) {
                lease.addUnit(foundUnit);
                print = "Added unit #" + foundUnit.getSerialNumber() + " : " + foundUnit.getMachinery().getName() + "\n";
                print += " Total price per month: " + lease.subtotal();
            }
            else 
            {
                print = "Unit #" + foundUnit.getSerialNumber() + "not availible.";
            }
        }
        else 
        {
            print = "Error: Unit does not exist.";
        }
        return print;
    }
    
    

    public String startRemoveUnit() 
    {
        String print = null;

        System.out.println("\nEnter serial number: ");        
        Scanner sc = new Scanner(System.in);
        String serialNumber = sc.next();       

        Unit foundUnit = machineryCtr.findUnit(serialNumber);
        if(foundUnit != null) 
        {
            lease.removeUnit(foundUnit);
            foundUnit.setAvailibility(true);
            print = "Removed item #" + ".";

        }
        else 
        {
            print = "Error: Unit does not exist.";
        }
        return print;
    }

    public String startSetCustomer() 
    {
        String print = null;

        System.out.println("Enter customer ID: ");
        Scanner sc = new Scanner(System.in);
        String id = sc.next();

        Customer foundCustomer = customerCtr.findCustomer(id);
        if(foundCustomer != null) 
        {
            lease.setCustomer(foundCustomer);
            print = "Customer successfully assigned to the sale:" + "\n"
            + " Name: " + foundCustomer.getName() + "\n"
            + " Address: " + foundCustomer.getAddress() + "\n"
            + " Phone: " + foundCustomer.getPhone() + "\n"
            + " E-mail: " + foundCustomer.getEmail() + "\n"
            + " Type: " + foundCustomer.getType();
        }
        else 
        {
            print = "Error: Customer does not exist.";
        }
        return print;
    }

    public String startSetDiscount() 
    {
        String print = null;

        boolean access = false;

        Scanner sc = new Scanner(System.in);

        if(securityLvl < 2) 
        {
            while(access == false) 
            {
                System.out.println("ACCESS DENIED! Enter password: ");                
                String password = sc.nextLine();

                if(password.equals(masterPassword)) 
                {
                    access = true;
                }
            } 

        }
        else 
        {
            access = true;
        }

        if(access == true) 
        {
            System.out.println(" Current discount: " + lease.getDiscount() + "%");
            System.out.println(" Enter new discount (maximum " + Lease.getMaxDiscount() + "%): ");
            int discount = sc.nextInt();
            lease.setDiscount(discount);

            print = "Discount for lease #" + lease.getId() + " has been set to " + lease.getDiscount() + "%." + "\n"
            + " Updated price per month: kr" + lease.subtotal();

        }
        return print;
    }

    public String startSetPeriod() 
    {
        String print = null;

        System.out.println("Enter period (number of days): ");
        Scanner sc = new Scanner(System.in);
        int period = sc.nextInt();

        if(period > 1) 
        {
            lease.setPeriod(period);
            print = "Period has been set to " + period + " days.";
        }
        else 
        {
            print = "Error, period must be greater than 1";
        }
        return print;
    }

    public String startConfirmLease() 
    {
        String print = null;
        if(lease.getPeriod() != 0) {
            for(Unit unit : lease.getUnitList()) 
            {
                unit.setAvailibility(false);
            }

            addLease(lease);

            print = " Lease #" + lease.getId() + " has been registered as active.";
        }
        else 
        {
            print = "Error: Period and/or Customer not set.";
        }
        return print;
    }

    // Find/Edit Menu 
    public String findEditMenu() 
    {
        String print = null;

        boolean exit = false;
        print = leaseFindStart();
        if(lease == null) 
        {
            exit = true;
        }
        while(!exit) 
        {
            writeFindEditMenu(print);
            int choice = getChoice();

            if(choice == 1) 
            {
                print = leasePrintInfo();
            }
            else if(lease.getState().equals("active")) {
                if(choice == 2)
                {
                    print = startSetDiscount();

                }
                else if(choice == 3) 
                {
                    print = startSetPeriod();
                }
                else if(choice == 4) 
                {
                    print = startSetCustomer();
                }
                else if(choice == 5) 
                {
                    print = startRegisterReturn();
                }
                else if(choice == 6 && securityLvl == 3) 
                {
                    print = startDeleteLease();
                }
            }
            else if(securityLvl == 3) 
            {
                if(choice == 2)
                {
                    print = startDeleteLease();

                }
            }

            if(choice == 0) 
            {
                print = null;
                exit = true;
            }
        }

        return print;
    }

    public String leaseFindStart() 
    {

        String print = null;
        System.out.print("\nEnter id: ");

        Scanner sc = new Scanner(System.in);
        String id = sc.next();
        lease = null;
        lease = findLease(id);
        if(lease == null) 
        {
            print = "ERROR: Lease not found.";
        }
        return print;

    }

    private void writeFindEditMenu(String print) 
    {
        System.out.println("\f *** LEASE ID: " + lease.getId() + " ***");
        System.out.println(" (1)Show information");
        if(lease.getState().equals("active")) {            
            System.out.println(" (2)Update discount");
            System.out.println(" (3)Update period");
            System.out.println(" (4)Set customer");
            System.out.println(" (5)Register return");
            if(securityLvl == 3) 
            {
                System.out.println(" (6)Delete");
            }
        }
        else if (securityLvl == 3)
        {
            System.out.println(" (2) Delete");
        }

        System.out.println(" (0)Back");
        if(print != null) 
        {
            System.out.println("\n " + print);

        }
        System.out.print("\n Make your choice: ");
    }

    public String leasePrintInfo() 
    {
        String print = null;
        print = " #Lease: #" + "\n" 
        + "  ID: " + lease.getId() + "\n"
        + "  Date: " + lease.getLeaseDate() + "\n"
        + "  Customer ID: " + lease.getCustomer().getId() + "\n"
        + "  Customer name: " + lease.getCustomer().getName() + "\n";

        print += "  STATE: " + lease.getState() + "\n"
        + "  -- \n"
        + "  SUMMARY:";

        int counter = 1;
        for(Unit unit : lease.getUnitList()) 
        {
            print += "\n  " + counter + ": " + unit.getMachinery().getName();
            counter++;
        }

        print += "\n  -- \n"
        + "  Discount: " + lease.getDiscount() + "%\n"
        + "  -- \n"
        + "  Total per month: kr" + lease.subtotal();
        return print;
    }

    public String startRegisterReturn() 
    {
        String print = null;
        String state = null;
        int difference = checkReturn();

        if(difference <= lease.getPeriod()) 
        {
            state = "inactive - returned on time";
            lease.setState(state);

        }
        else 
        {
            int daysLate = difference - lease.getPeriod();
            state = "inactive - returned " + daysLate + " days late";
            lease.setState(state);

        }
        for(Unit unit : lease.getUnitList()) 
        {
            unit.setAvailibility(true);
        }
        print = "Return of lease #"+ lease.getId() + " has been registered as '" + state + "'." ;

        return print;     

    }

    private int checkReturn() 
    {
        DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
        Date dateobj = new Date();

        String leaseDate = lease.getLeaseDate();
        String returnDate = df.format(dateobj);

        String[] leaseDateArray = leaseDate.split("-");
        String[] returnDateArray = returnDate.split("-");

        int leaseDays = Integer.parseInt(leaseDateArray[0]) + 30 * Integer.parseInt(leaseDateArray[1]) + 365 * Integer.parseInt(leaseDateArray[2]);
        int returnDays = Integer.parseInt(returnDateArray[0]) + 30 * Integer.parseInt(returnDateArray[1]) + 365 * Integer.parseInt(returnDateArray[2]);

        int result = returnDays - leaseDays;
        return result;
    }

    public String startDeleteLease() 
    {
        deleteLease(lease);
        return "Lease #" + lease.getId() + " has been deleted.";
    }
}
